// pages/components/Version/version.js
import { request, fomatForCollect, upRequest, wxuuid,getTotalSize} from "../../../utils/util.js"
const { $Message } = require('../../../dist/base/index');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sureTitle:"",
    sureContent:"", 
    sureType:"",//用于确认框的描述
    data: {},
    visible: false,
    actions: [
      {
        name: '取消'
      },
      {
        name: '确定',
        color: '#ed3f14',
        loading: false
      }
    ],
    id: "",//等待回退的版本号
    show: false,
    buttons: [
      {
        type: 'default',
        className: '',
        text: '取消',
        value: 0
      },
      {
        type: 'primary',
        className: 'sure',
        text: '确定',
        value: 1,
        color: "#487FF8"
      }
    ],
    newVersion: null,
    tempFile: [],//临时文件
    textArea: "",//文本域内容
    fileSize:"",//文件大小



  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const data = JSON.parse(options.data)
   
    this.setData({
      data: data
    })
    this.getMax(data)
    
  },

  /**
   * 获取最大值的方法
   */
  getMax(val) {
    let arr = [];
    arr.push(Number(val.version))
    
    val.old_doc.forEach(item => {
      arr.push(item.version)
    })
    const maxVersion = Math.max(...arr)
    const newVersion = (maxVersion + 0.1).toFixed(1)
    this.setData({
      ...this.data,
      newVersion: newVersion
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 历史版本预览
   */
  preview(e) {
    
    const param = {
      file_hash: e.currentTarget.dataset.uuid
    }
    request("POST", "/api/upload/doc/preview/", param, "", true)
      .then(res => {
        if (res.statusCode === 200) {
          wx.navigateTo({
            url: `/pages/webView/preview/preview?url=${encodeURIComponent(res.data.url)}`,
          })
        }
      })
  },
  /**
   * 历史版本分享
   */
  share(e) {
    const data = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/components/Share/share?type=${data.types}&name=${data.name}&uuid=${data.uuid}`,
    })
  },
  /**
   * 版本回退
   */
  vBack(e) {
    this.handleOpen(e.currentTarget.dataset.id,"back");
  },

  /**
   * 删除操作
   * @param {*} param 
   */
  delete(e){
    this.handleOpen(e.currentTarget.dataset.id,"delete");
  },
  /**
   * 回退操作
   */
  handleOpen(param,type) {
    if(type === "back"){
      this.setData({
        visible: true,
        id: param,
        sureTitle:"回退确认",
        sureContent:"确认要将该版本还原为最新版吗",
        sureType:"back"
      });
    }else{
      this.setData({
        visible: true,
        id: param,
        sureTitle:"删除确认",
        sureContent:"确认要将该版本删除吗",
        sureType:"delete",
      });
    }
    
  },

  handleClick({ detail }) {
    const that = this
    const type = this.data.sureType
    if(type === "back"){
      if (detail.index === 0) {
        this.setData({
          visible: false
        });
      } else {
        const action = [...this.data.actions];
        action[1].loading = true;
        this.setData({
          actions: action
        });
        const param = {
          old_docid: this.data.id,
          status: 0
        }
        request("PATCH", `/api/service/docinfo/${this.data.data.id}/`, param)
          .then(res => {
            if(res.statusCode === 427){
              action[1].loading = false;
              that.setData({
                visible: false,
                actions: action
              });
            }
            if (res.statusCode == 200) {
              action[1].loading = false;
              that.setData({
                visible: false,
                actions: action
              });
              wx.navigateBack({
                delta: 1,
                success: res => {
                  const showMsg = setTimeout(()=>{
                    $Message({
                      content: '回退成功！',
                      type: 'success'
                    });
                    clearTimeout(showMsg)
                  },250)
                  
                }
              })
            }
          })
      }
    }else{
      if (detail.index === 0) {
        this.setData({
          visible: false
        });
      } else {
        const action = [...this.data.actions];
        action[1].loading = true;
        this.setData({
          actions: action
        });
        const param = {
          deleteid:[this.data.id]
        }
        request("DELETE", `/api/service/docinfo/multiple_delete/`,param)
          .then(res => {
            if(res.statusCode === 427){
              action[1].loading = false;
              that.setData({
                visible: false,
                actions: action
              });
            }
            if (res.statusCode == 200) {
              const newData = that.data.data.old_doc
              newData.map((item,index) =>{
                if(item.id === that.data.id){
                    newData.splice(index,1)
                }
              })
              action[1].loading = false;
              that.setData({
                visible: false,
                actions: action,
                data:{
                  ...that.data.data,
                  old_doc:newData
                }
              });
              $Message({
                content: '删除成功！',
                type: 'success'
              });
            }
          })
      }
    }
   
  },
  up() {
    this.setData({
      show: true
    })
  },
  /**
   * 半屏弹窗上的按钮
   * @param {*} e 
   */
  chooseFile() {
    const that = this
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success(res) {
        
        const tempFile = res.tempFiles[0]
        that.setData({
          ...that.data,
          tempFile: tempFile,
          fileSize:tempFile.size
        })
      },
      fail() {

      }
    })
  },
  /**
   * 文本域的input事件
   * @param {*} e 
   */
  input(e) {
    this.setData({
      ...this.data,
      textArea: e.detail.value
    })
  },
  buttontap(e) {
    const that = this
   
    if (e.detail.index === 0) {
      this.setData({
        show: false,
        textArea: "",
        tempFile: []
      })
    } else {
      if (this.data.tempFile.length === 0) {
        wx.showToast({
          title: '请选择文件',
          icon: "none"
        })
      } else {
        this.setData({
          ...this.data,
          show: false
        })
        if(this.data.classifyType === "uesr"){
          const availableCapacity = wx.getStorageSync('availableCapacity') //获取可用容量
          if(file_size > availableCapacity){
            wx.showToast({
              title: '个人容量不足',
              icon:"none"
            })
            that.setData({
              show: false,
              textArea: "",
              tempFile: []
            })
            that.handleCancel1();
            return
          }
        }
        const tempFile = this.data.tempFile
        const verify_file_hash = wxuuid()
        const param = {
          file_hash: verify_file_hash,
          file_catalog: that.data.parent,
          file_size:that.data.fileSize
        }
        request("POST", "/api/upload/verify/", param)
        .then(res =>{
          if(res.data.detail){
            wx.showToast({
              title: res.data.detail,
              icon:'none'
            })
            that.setData({
              show: false,
              textArea: "",
              tempFile: []
            })
            return
          }
          if(res.statusCode === 427){
            that.setData({
              show: false,
              textArea: "",
              tempFile: []
            })
          }
          if(res.statusCode === 200){
            $Message({
              content: `正在上传(0/1)`,
              duration: 999
            });
            const chunk_hash = wxuuid() + "-0"
            const file_hash = wxuuid()
            const param = {
              chunk_hash: chunk_hash,
              file_hash: file_hash
            }
            const file_name = tempFile.name
            const size = tempFile.size
            upRequest("/api/upload/upload_chunk/", "chunk", tempFile.path, param).then(res => {
              if (res.statusCode === 200) {
               
                const params = {
                  total_size: size,
                  file_catalog: that.data.data.catalog,
                  file_hash: file_hash,
                  file_name: file_name,
                  version: that.data.newVersion,
                  file_id: that.data.data.file_id,
                  abstract: that.data.textArea
                }
                request("POST", "/api/upload/merge/", params).then(res => {
                  if (res.statusCode === 200) {
                    wx.navigateBack({
                      delta: 1,
                      success: res => {
                        const showMsg = setTimeout(()=>{
                          $Message({
                            content: "新版本上传完成",
                            type: 'success',
                            duration: 2
                          });
                          clearTimeout(showMsg)
                        },250)
                        
                      }
                    })
                  }
                })
              }
            }).catch(error => {
              
            })
          }
        })
        
      }
    }
  },

})